
export type XHR_Response = {
  status: number;
  response: XMLHttpRequestResponseType,
  headers: any,
  time_ms: number
};
export type XHR_Callback = (response: XHR_Response) => void;
export class XHR {
  public static Get(uri: string, callback: XHR_Callback): void {
    const _xhr = new XHR("GET", uri);
    _xhr.send(null, callback);
  }
  public static Post(uri: string, data: Document | XMLHttpRequestBodyInit | null, callback: XHR_Callback): void {
    const _xhr = new XHR("POST", uri);
    _xhr.send(data, callback);
  }

  protected xhr: XMLHttpRequest;
  constructor(method: string, uri: string) {
    this.xhr = new XMLHttpRequest();
    this.xhr.open(method, uri, true);
  }

  public AddHeader(key: string, value: string): XHR {
    this.xhr.setRequestHeader(key, value);
    return this;
  }

  public send(data: Document | XMLHttpRequestBodyInit | null, callback: XHR_Callback) {
    const time_req_start = performance.now();
    this.xhr.onreadystatechange = function () {
      if (this.readyState == 4) {
        const time_req_end = performance.now();
        callback({
          status: this.status,
          response: this.response,
          headers: this.getAllResponseHeaders(),
          time_ms: time_req_end - time_req_start
        });
      }
    };
    this.xhr.send(data);
  }
}